#!/usr/bin/ruby
# -*- coding: utf-8 -*-

## monkey patch
class File
  def self.write(filename, data, offset=0)
    File.open(filename, 'w') do |fh|
      fh.seek(offset)
      fh.write(data)
    end
  end
end

module SmugMug
  class AutoGen
    extend Forwardable

    def_delegator :@types, :each, :each
    def_delegator :@types, :sort, :sort    

    def initialize(filename, name)
      @types = []
      @name = name

      doc = REXML::Document.new(File.open(filename))
      doc.root.each_element('type') do |e|
        h = {
          :name       => e.attributes['name'],
          :read_only => (e.attributes.has_key?('read-only') ? e.attributes['read-only'] : false)
        }

        klass = SmugMug::Type::Base.factory(e.attributes['type'], h)
        @types << klass
      end
    end

    def to_s
      s  = ""
      s += sprintf(HEADER, @name)
      s += @types.sort.join("\n")
      s += FOOTER
    end
  end
end
